package liuwh.mina.basic.tcp.server.tiemserver.codec;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import liuwh.mina.basic.tcp.server.tiemserver.TimeResponse;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class TimeResponseEncoder extends ProtocolEncoderAdapter {

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		
		TimeResponse res = (TimeResponse) message;
		
		IoBuffer buff = IoBuffer.allocate(32);
		buff.setAutoExpand(true);
		buff.setAutoShrink(true);
		
		
		CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
		buff.putString(res.getClient() + " 您好！服务器时间是：", encoder);
		
		Date date = res.getDate();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd，HH时mm分ss秒");
		
		buff.putString(sdf.format(date), encoder);
		buff.put((byte)'\n');
		
		buff.flip();
		
		out.write(buff);
		out.flush();
		
		System.err.println("res encode end .... ");
	}

}
